package org.dromara.device.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.RequiredArgsConstructor;
import org.dromara.basic.domain.FaceImage;
import org.dromara.basic.domain.bo.FaceImageBo;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.FaceImageVo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.service.IDictService;
import org.dromara.basic.service.IMemberService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.device.domain.bo.SendToServer;
import org.dromara.device.domain.dto.DeviceStatus;
import org.dromara.pe.domain.bo.AchievementBo;
import org.dromara.pe.domain.vo.AchievementVo;
import org.dromara.run.service.IDeptService;
import org.dromara.utils.service.SynchronizeImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/device/api")
public class DeviceController extends BaseController {
    // 注入线程池
    @Autowired
    @Qualifier("globalThreadPool")
    private ExecutorService globalThreadPool;
    private final SynchronizeImageService synchronizeImageService;
    private final IMemberService iMemberService;

    private final IDictService iDictService;
    /**
     * 查询设备信息
     */
//    @SaCheckPermission("device:api:version")
//     @SaIgnore
    @GetMapping("/info")
    public R<?> getDeviceInfo() {
        List<String> deviceServiceIp = iDictService.getDictValue("device_service_ip");
        //将字符串转成数组的形式
        JSONArray deviceStatusArray = new JSONArray();
        if(CollectionUtils.isNotEmpty(deviceServiceIp)){
            for(String ip:deviceServiceIp){
                String url = "http://" + ip + "/api/v1/ops/version";
                SendToServer sendToServer=new SendToServer();
                sendToServer.setUrl(url);
                sendToServer.setMethod("GET");
                String s = synchronizeImageService.sendGetOrPostRequest(sendToServer);
                // todo 该判断分支少了在线情况 按数据结构返回
                if(!"1".equals(s)){
                    // 设备连接失败时 设置状态位 及状态描述
                    deviceStatusArray.add(new DeviceStatus(ip,0, "成功",s));
                }else{
                    deviceStatusArray.add(new DeviceStatus(ip,1, "设备不在线,请检查设备",null));
                }
            }
        }else {
            return R.fail("无设备，请配置数据");
        }

        return R.ok(deviceStatusArray);
    }
    /*
    * 查询设备内详细信息
    * */
    @SaIgnore
    @GetMapping("/status/info")
    public R<?> getDeviceStatusInfo(@RequestParam("deviceIp") String deviceIp) {
        String url = "http://" + deviceIp + "/api/v1/ops/status";
        SendToServer sendToServer=new SendToServer();
        sendToServer.setUrl(url);
        sendToServer.setMethod("GET");
        String s = synchronizeImageService.sendGetOrPostRequest(sendToServer);
        if(!"1".equals(s)){
            return R.ok(s);
        }
        return R.fail("设备不在线，请检查设备");
    }
    /*
    * 查询设备状态
    * */

//    @SaCheckPermission("device:api:status")
    @SaIgnore
    @GetMapping("/status")
    public R<?> getDeviceStatus(@RequestParam("deviceIps") String deviceIps) {
        //将字符串转成数组的形式
        String[] deviceIpList = deviceIps.split(",");
        Map<String,Boolean> map=new LinkedHashMap<>();
        for(String ip:deviceIpList){
            String url = "http://" + ip + "/api/v1/ops/version";
            SendToServer sendToServer=new SendToServer();
            sendToServer.setUrl(url);
            sendToServer.setMethod("GET");
            String s = synchronizeImageService.sendGetOrPostRequest(sendToServer);
            if(!"1".equals(s)){
                map.put(ip,true);
            }else {
                map.put(ip,false);
            }
        }
        return R.ok(map);
    }
    /*
    * 查询学生底图信息是否在设备里
    * */
    @SaIgnore
    @PostMapping("/exists")
    public R<?> getDeviceImageExists(@RequestBody FaceImageBo bo) {
        // 使用线程安全的队列来存储 FaceImage 对象
        Queue<MemberVo> faceImagesQueue = new ConcurrentLinkedQueue<>();
        List<Future<?>> futures = new ArrayList<>();
        List<MemberVo> list=new ArrayList<>();
        Map<String,List<String>> stringListMap=new HashMap<>();
        if(CollectionUtils.isEmpty(bo.getStuNums())){
            MemberBo memberBo=new MemberBo();
            memberBo.setClassId(bo.getClassId());
            List<String> collect = iMemberService.queryList(memberBo).stream()
                .map(MemberVo::getIdNumber)
                .collect(Collectors.toList());
            bo.setStuNums(collect);
        }
        stringListMap.put("uids",bo.getStuNums());

        for(String ip:bo.getDeviceIps()){
            String url = "http://" + ip + "/api/v1/uid/query/exists";
            Object json = JSONObject.toJSON(stringListMap);
            String respon = synchronizeImageService.sendPostRequest(url, json);
            if(!"1".equals(respon)){
                JSONObject jsonObject = JSONObject.parseObject(respon);
                String message = jsonObject.getString("data");
                JSONArray result = JSON.parseArray(message);
                for(Object object:result){
                    Runnable task = () -> {
                        JSONObject jsonObject1 = JSONObject.parseObject(object.toString());
                        MemberVo memberVo = iMemberService.queryByIdNumber(jsonObject1.get("uid").toString());
                        if(ObjectUtil.isNotNull(memberVo)){
                            memberVo.setIsImageExit((Boolean) jsonObject1.get("exist"));
                            faceImagesQueue.add(memberVo);
                        }
                    };
                    // 提交任务到线程池
                    Future<?> future = globalThreadPool.submit(task);
                    futures.add(future);

                }
                // 等待所有任务完成
                for (Future<?> future : futures) {
                    try {
                        future.get(); // 阻塞，直到任务执行完成
                    } catch (ExecutionException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                // 将所有收集到的 FaceImage 对象插入数据库
                if (!faceImagesQueue.isEmpty()) {
                    list=faceImagesQueue.stream().toList();
                }
            }else {
                return R.fail("设备不在线，请检查设备");
            }

        }
        return R.ok(list);
    }
    /*
    * 调试龙山书院的接口
    * */
    @SaIgnore
    @PostMapping("/debug/server")
    public R<?> sendToServer(@RequestBody SendToServer sendToServer) {
        String s = synchronizeImageService.sendGetOrPostRequest(sendToServer);
        if(!"1".equals(s)){
            return  R.ok(s);
        }
        return R.fail("请求超时");
    }
}
